

package com.hulk.ratel.config.tenant;

import cn.hutool.core.util.StrUtil;


import com.hulk.ratel.constant.Constants;
import com.netflix.discovery.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hulk
 * @date 2018/9/13
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TenantContextHolderFilter extends GenericFilterBean {

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;


		//TODO   //最好的方法是合作方号，后8位标识租户ID最好， 这样解决了， 数据库合作方号+流水的唯一问题 ,feign 多租户过滤器后面完善.


		String tenantId = request.getHeader(Constants.TENANT_ID);
		log.debug("获取header中的租户ID为:{}", tenantId);

		if (StrUtil.isNotBlank(tenantId)) {
			TenantContextHolder.setTenantId(Long.parseLong(tenantId));
		} else {
			TenantContextHolder.setTenantId(0L);
		}

		filterChain.doFilter(request, response);
		TenantContextHolder.clear();
	}
}
